package com.lancoo.ccas53.schedules;

import cn.hutool.core.io.FileUtil;
import com.alibaba.fastjson.JSON;
import com.lancoo.ccas53.entity.TeachingClassStudent;
import com.lancoo.ccas53.pojo.constant.GlobalConstant;
import com.lancoo.ccas53.service.impl.StudentServiceImpl;
import com.lancoo.ccas53.util.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.File;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Author: mabolin
 * @Date: 2024-09-04-10:48
 * @Description:
 */
@Slf4j
@Component
@EnableAsync(proxyTargetClass = true)
public class RedisToSql {
    @Resource
    private StudentServiceImpl studentServiceImpl;
    @Resource
    private RedisUtil redisUtil;

    @Scheduled(cron = "0 57,59 23 * * ?")
    public void saveRedisSelectData() {
        log.info("================系统开启定时任务: 保存redis学生选课数据 开始================");
        String redisKey = studentServiceImpl.getCacheKeys(2000029, null, 3, null);
        Map<Object, Object> hmget = redisUtil.hmget(redisKey);
        Collection<Object> values = hmget.values();
        List<TeachingClassStudent> redisList = new ArrayList<>();
        for (Object value : values) {
            TeachingClassStudent model = (TeachingClassStudent) value;
            redisList.add(model);
        }
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String filePath = GlobalConstant.OUTPUT_EXCEL_PATH + dateFormat.format(new Date()) + "/ccas-redis.txt";
        File folder = new File(filePath);
        String jsonString = JSON.toJSONString(redisList);
        FileUtil.writeString(jsonString, folder, StandardCharsets.UTF_8);
        log.info("================系统开启定时任务: 保存redis学生选课数据 结束================");
    }

}
